package com.sky.aop;
import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
        //获得方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获得方法
        Method method = signature.getMethod();
        //获得方法上的注解
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        log.info("自动填充操作:{}",operationType);


        //获得增强方法的参数
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length ==0){
            log.info("增强方法没有参数或长度为零");
            return;
        }
        Object entry =args[0];
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        if(operationType==OperationType.INSERT){
            try {
                log.info("插入的自动填充");
                Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                setCreateTime.invoke(entry,now);
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);
                Method setCreatUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
                setCreatUser.invoke(entry,currentId);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,currentId);
            }catch (Exception e){
                log.info("没有找到相应的set方法");
                e.printStackTrace();
            }
        }else {
            try {
                log.info("更新的自动填充");
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,currentId);
            }catch (Exception e){
                log.info("没有找到相应的set方法");
                e.printStackTrace();
            }
        }
    }
}
